package com.tm.controller;

import com.tm.service.UserTanhuaService;
import com.tm.util.AliOSSUtil;
import com.tm.util.NearDistanceUtil;
import org.apache.tomcat.util.http.ConcurrentDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import tm.pojo.MemberMp3;
import tm.pojo.NearMember;
import tm.pojo.UserPojo;
import tm.pojo.dto.AllLoveQuestionAndAnswerDTO;
import tm.pojo.dto.HomePageDto;
import tm.pojo.dto.LoveResultAnswer;
import tm.pojo.dto.TodayGirlDto;
import tm.result.Result;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Rocky
 * @create 2022-09-26 11:49
 */
@RestController
@RequestMapping("login")
public class UserTanhuaController {

    @Autowired
    private UserTanhuaService userTanhuaService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("getId")
    public Result getId(String v){
        String sysYear = getSysYear();
        String s = autoFill(v, 4);
        String jack=sysYear+s;
        redisTemplate.opsForValue().set(jack,1111);
        Object o = redisTemplate.opsForValue().get(jack);
        String s1 = o.toString();
        return Result.SUCCESS(s1);
    }


    public long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }


    public static String autoFill(String v,int fillLength) {
        int length = v.length();
        if (length >= fillLength) {
            return v;
        }
        int rest = fillLength - length;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < rest; i++) {
            sb.append('0');
        }
        sb.append(v);
        return sb.toString();
    }


    public static String getSysYear() {
        Calendar date = Calendar.getInstance();
        String year = String.valueOf(date.get(Calendar.YEAR));
        return year;
    }




    //点击按钮喜欢该录音
    @PostMapping("queryMemberByLookMp3User")
    public Result queryMemberByLookMp3User(){
        return userTanhuaService.queryMemberByLookMp3User();
    }

    //随机接收录音
    @PostMapping("queryMemberMp3")
    public Result queryMemberMp3(Integer userId){
        return userTanhuaService.queryMemberMp3(userId);
    }

    //查询录音条数
    @PostMapping("queryMp3Count")
    private Result queryMp3Count(Integer userId){
        return userTanhuaService.queryMp3Count(userId);
    }

    //上传录音
    @PostMapping("addMemberMp3")
    private Result addMemberMp3(Integer userId, MultipartFile userMp3) throws IOException {
        String upload = AliOSSUtil.upload(userMp3);
        Integer flg = (Integer) queryMp3Count(userId).getData();
        if (flg>=10){
            return Result.ERROR(999,"今日上传录音已达上限");
        }
        MemberMp3 memberMp3 = new MemberMp3();
        memberMp3.setUserId(userId);
        memberMp3.setMp3Url(upload);

        return userTanhuaService.addMemberMp3(memberMp3);
    }

    //更新当前位置
    @PostMapping("updateMyLocation")
    public Result updateMyLocation(Integer uid,Double lon,Double lat){
        redisTemplate.opsForHash().put("address","user_"+uid,lon+","+lat);
        return Result.SUCCESS();
    }

    //传入自己距离,根据经纬度得到附近人信息
    @PostMapping("queryNearMember")
    public Result queryNearMember(Integer userId){
        //取得Redis中用户存进去的Hash键
        Map address = redisTemplate.opsForHash().entries("address");
        //根据Hash键获取到自己的用户id
        String str =(String)address.get("user_" + userId);
        NearMember aaa = aaa(str);//自己的经纬度
        //遍历
        List<NearMember> list = new ArrayList<>();
        //获取到这个键中的所有键值对
        Set set = address.keySet();
        //遍历这些键值对
        set.forEach(a->{
            //分割key 只需要后面的userID
            Integer NearuserId = Integer.parseInt(a.toString().substring(5)) ;
            //如果得到的UserId中不包含传入的userid就进入
            if (!NearuserId.equals(userId)){
                String s = address.get(a).toString();
                NearMember aaa1 = aaa(s);
                aaa1.setUserId(NearuserId);
                list.add(aaa1);
            }
        });
        //list里有所有附近的人的经纬度
        //循环得到所有人离我的距离
        list.forEach(a->{
            double v = NearDistanceUtil.GetDistance(aaa.getLon(), aaa.getLat(), a.getLon(), a.getLat());
            a.setDistance(v);
        });
        //排序 根据Stream流中提供的过滤方法 查询到距离在五公里以内的用户正序排序
        List<NearMember> collect = list.stream().filter(a -> a.getDistance() <= 5000).sorted(Comparator.comparing(NearMember::getDistance)).collect(Collectors.toList());
        List<UserPojo>list1=new ArrayList<>();
        //将查询到的附近人数据的用户id获取到然后进行循环 到数据库中查询获得用户详细的信息
        for (int i = 0; i < collect.size(); i++) {
            NearMember nearMember = collect.get(i);
            Integer userId1 = nearMember.getUserId();
            Double distance = nearMember.getDistance();
            UserPojo userPojo=userTanhuaService.queryUser(userId1);
            userPojo.setDistance(distance);
            list1.add(userPojo);
        }
        return Result.SUCCESS(list1);
    }

    //获取附近人距离提取的分割方法
    private NearMember aaa(String str){
        String[] split = str.split(",");
        double lon = Double.parseDouble(split[0]);
        double lat = Double.parseDouble(split[1]);
        NearMember nearMember = new NearMember();
        nearMember.setLat(lat);
        nearMember.setLon(lon);
        return nearMember;
    }

    //进行灵魂偶遇
    @PostMapping("soulMeet")
    public Result soulMeet(Integer userId){
        return userTanhuaService.soulMeet(userId);
    }

    //查看用户历史测试记录
    @PostMapping("queryLoveTestingRecord")
    public Result queryLoveTestingRecord(Integer userId){
        return userTanhuaService.queryLoveTestingRecord(userId);
    }


    //灵魂测试 接收用户数据
    @PostMapping("queryLoveResult")
    public Result queryLoveResult(@RequestBody LoveResultAnswer loveResultAnswer){
        return userTanhuaService.queryLoveResult(loveResultAnswer);
    }

    //查看12个情感测试题
    @PostMapping("queryLoveTesting")
    public Result queryLoveTesting(){
        return userTanhuaService.queryLoveTesting();
    }

    //查看探花主页最近来访的的信息
    @PostMapping("thHomePage")
    public Result thHomePage(@RequestBody HomePageDto homePageDto){
        return userTanhuaService.thHomePage(homePageDto);
    }

    //查看今日佳人
    @PostMapping("getTodayGirl")
    public Result getTodayGirl(@RequestBody TodayGirlDto todayGirlDto){
       return userTanhuaService.getTodayGirl(todayGirlDto);
    }

}
